package wechat

import (
	"ai-bot/args"
	"ai-bot/common"
	"ai-bot/entity"
	bytes2 "bytes"
	"encoding/json"
	"fmt"
	"github.com/opentdp/wrest-chat/httpd/wcfrest"
	"github.com/opentdp/wrest-chat/wcferry"
	"net/http"
	"strings"
	"time"
)

/*
发送 消息到微信
*/
func SendToWeChat(bytes []byte, url string, method string) string {
	fmt.Println("send to wechat start......")
	client := &http.Client{}
	req, err := http.NewRequest(method, url, bytes2.NewBuffer(bytes))

	if err != nil {
		fmt.Println(err)
		return ""
	}
	req.Header.Add("accept", "application/json")
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer res.Body.Close()
	fmt.Println("send to wechat end......")
	return ""
}

// wxid_lbunvy9cymea22

func GetUserInfoByWxid(wxid string, blue7 *entity.Blue7Bot) entity.UserInfo {
	if c, ok := blue7.UserInfoMap[wxid]; ok {
		return c
	}

	request := wcfrest.GetInfoByWxidRequest{
		Wxid: wxid,
	}

	bytes, err := json.Marshal(&request)
	if err != nil {
		fmt.Println(err)
		//returnn nil
	}
	body := common.Post(bytes, "http://localhost:7600/wcf/user_info", "POST")
	if body == nil {
		return entity.UserInfo{}
	}
	contact := entity.UserInfo{}
	json.Unmarshal(body, &contact)
	blue7.UserInfoMap[wxid] = contact
	return contact

}

func GetSelfInfo(blue7 *entity.Blue7Bot) *entity.UserInfo {
	if blue7.SelfInfo != nil {
		return blue7.SelfInfo
	}

	body := common.Post(nil, "http://localhost:7600/wcf/self_info", "POST")
	if body == nil {
		return nil
	}
	contact := entity.UserInfo{}
	json.Unmarshal(body, &contact)
	blue7.SelfInfo = &contact
	return &contact

}

/**

// 艾特一个人
//  map[msgsource:map[atuserlist:wxid_fitxnaxdc83s22 membercount:4 pua:1 signature:V1_kmLTFoXU|v1_kmLTFoXU silence:0 tmp_node:map[publisher-id:]]]
// 艾特多个人
// map[msgsource:map[atuserlist:wxid_2qhmyothjjdr22,wxid_fitxnaxdc83s22 membercount:4 pua:1 signature:V1_w98PnpH5|v1_w98PnpH5 silence:0 tmp_node:map[publisher-id:]]]
// 没有艾特人
// map[msgsource:map[membercount:4 pua:1 signature:V1_lJsX16iy|v1_lJsX16iy silence:0 tmp_node:map[publisher-id:]]]


*/
// isAt 判断是否被艾特，返回 被艾特列表的人的 wxid，多个人就根据 逗号分割
func IsAt(xml any) (string, bool) {
	m, ok := xml.(map[string]interface{})
	//fmt.Println("m:  ", m)
	//fmt.Println("ok: ", ok)
	if !ok {
		return "", false
	}
	fmt.Println("m is ok..")
	if msgsource, ok1 := m["msgsource"].(map[string]interface{}); ok1 {
		for k, v := range msgsource {
			fmt.Println(k, " = ", v)
			/**
				没有 艾特人
				pua  =  1
				signature  =  V1_f/l9sV13|v1_f/l9sV13
				silence  =  0
				tmp_node  =  map[publisher-id:]
				membercount  =  4

			艾特多人：
				atuserlist  =  wxid_2qhmyothjjdr22,wxid_8u00lfu9zheu22
				membercount  =  4
				pua  =  1
				signature  =  V1_QG0Sx+H8|v1_QG0Sx+H8
				silence  =  0
				tmp_node  =  map[publisher-id:]
			*/
		}
		v, ok2 := msgsource["atuserlist"]
		if ok2 {
			return v.(string), ok2
		}
	}
	return "", false
}

func HandleMsg(blue7 entity.Blue7Bot, f common.CallAi) {
	go func() {
		for {
			fmt.Println("heart....")
			time.Sleep(time.Second * 10)
		}
	}()
	for {
		select {
		case msg := <-blue7.FlexWxMsgChan:
			var xml interface{} = msg.Xml
			at, b := IsAt(xml)
			if !b {
				continue
			}
			split := strings.Split(at, ",")
			userInfo := GetSelfInfo(&entity.Blue7Bot1)
			fmt.Println("self_wxid", userInfo.Payload.Wxid)
			if userInfo != nil {
				payload := userInfo.Payload
				wxid := payload.Wxid
				if common.IsContain(split, wxid) && common.IsContain(args.WeChat.Groups, msg.Roomid) {
					go sendMsg(msg, &blue7, f)
				}
			}

		default:
			//fmt.Println("heart....")
			time.Sleep(time.Second)
		}
	}
}

func sendMsg(msg wcferry.FlexWxMsg, blue7 *entity.Blue7Bot, f common.CallAi) {
	rpcContact := GetUserInfoByWxid(msg.Sender, blue7)
	name := rpcContact.Payload.Name

	if !msg.IsGroup {
		return
	}
	roomid := msg.Roomid

	request1 := wcfrest.SendTxtRequest{
		Msg:      "@" + name + "\n" + " 请稍等片刻。。。",
		Receiver: roomid,
		Aters:    []string{msg.Sender},
	}
	bytes1, _ := json.Marshal(&request1)
	SendToWeChat(bytes1, "http://localhost:7600/wcf/send_txt", "POST")

	content := msg.Content
	aiMsg := f(content.(string))

	// at 某人
	//// 发送文本信息
	//if ater != "" {
	//	if u := wc.CmdClient.GetInfoByWxid(ater); u != nil && u.Name != "" {
	//		msg = "@" + u.Name + "\n" + msg
	//	}
	//}
	//deepseekMsg
	aiMsg = "@" + name + "\n" + aiMsg
	request := wcfrest.SendTxtRequest{
		Msg:      aiMsg,
		Receiver: roomid,
		Aters:    []string{msg.Sender},
	}
	bytes, _ := json.Marshal(&request)
	SendToWeChat(bytes, "http://localhost:7600/wcf/send_txt", "POST")
}
